<template>
	<a-layout has-sider class="components-layout-custom">
	  <a-layout-sider 
		width="195" 
		v-model:collapsed="collapsed" 
		:trigger="null" 
		collapsible
		:style="{ overflow: 'auto', height: '100vh', position: 'fixed', left: 0, top: 0, bottom: 0, zIndex: '10' }"
	  >
		<div style="display: flex; align-items: center;">
		  <img src="../assets/EVP LOGO-01 1.png" style="width: 65px; height: 55px; margin-bottom: 5px;margin-left: 10px;">
		  <div class="logo" style="margin-top: 7px;">{{ $t('self.appName') }}</div>
		</div>
 
		<!-- 左侧菜单：用a-sub-menu实现下拉 -->
		<a-menu
		  mode="inline"
		  :selected-keys="selectedKeys"
		  :open-keys="openKeys"
		  @openChange="onOpenChange"
		  theme="dark"
		>
		  <template v-for="route in menuData" :key="route.path">
			<!-- 有子路由 → 渲染a-sub-menu作为下拉菜单 -->
			<a-sub-menu v-if="route.children && route.children.length" :key="route.path">
			  <template #title>
				<component :is="route.meta.icon" v-if="route.meta.icon" />
				<span>{{ $t(route.title) }}</span>
			  </template>
			  <!-- 子路由菜单项 -->
			  <a-menu-item 
				v-for="child in route.children" 
				:key="child.path" 
				@click="() => $router.push(child.path)"
			  >
				{{ $t(child.title) }}
			  </a-menu-item>
			</a-sub-menu>
  
			<!-- 无子路由 → 直接渲染a-menu-item -->
			<a-menu-item v-else :key="route.path" @click="() => $router.push(route.path)">
			  <component :is="route.meta.icon" v-if="route.meta.icon" />
			  <span>{{ $t(route.title) }}</span>
			</a-menu-item>
		  </template>
		</a-menu>
	  </a-layout-sider>
  
	  <!-- 主体区域 -->
	  <a-layout :style="{ marginLeft: '195px', position: 'relative' }">
		<a-layout-content class="main-wrapper base-flex base-columns" :style="{}">
		  <div class="collapsed-icon">
			<menu-unfold-outlined v-if="collapsed" class="trigger" @click="() => (collapsed = !collapsed)" />
			<menu-fold-outlined v-else class="trigger" @click="() => (collapsed = !collapsed)" />
		  </div>
		  <div class="base-ml15 base-mr15 base-pl25">
			<basic-right-bar ref="basicRightBarRef" :breadcrumb="breadcrumb" :title="rightBarTitle"></basic-right-bar>
		  </div>
		  <div class="content-wrapper base-flex1">
			<router-view />
		  </div>
		</a-layout-content>
	  </a-layout>
	</a-layout>
  </template>

  <script setup>
import { getCurrentInstance, nextTick, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from "vue-router"
import BasicRightBar from '@/layouts/BasicRightBar.vue'
import { mainStore } from '@/stores/mainStore'
import { flatAsyncRoutes } from '@/router/filterRouter'
import cloneDeep from 'lodash.clonedeep'
const { proxy } = getCurrentInstance()
const $TOOL = proxy.$TOOL
const $CONFIG = proxy.$CONFIG
const useMainStore = mainStore()

let collapsed = ref(false)
const route = useRoute()
const router = useRouter()
const rightBarTitle = ref('')
const basicRightBarRef = ref(null)
const breadcrumb = ref([]) 
const selectedKeys = ref([])
const openKeys = ref([])
const menuData = ref([])

// 监听侧边栏折叠状态
watch(collapsed, (curr) => {
  // 可根据需要调整主体margin-left，这里简化为固定155px
})

// 监听路由变化，初始化页面
watch(route, (curr) => {
  initPage(curr)
})

// 监听语言变化
watch(
  () => useMainStore.lang, 
  async () => {
    let allRoutes = await useMainStore.getUserMenus()
    useMainStore.resetRoutesLanguage(allRoutes)
    initPage(route)
  }
);

const onOpenChange = (keys) => {
  openKeys.value = keys.length ? [keys[keys.length - 1]] : []
}

onMounted(() => {
  initPage(route)
})

const initPage = (currentPageRoute) => {
  let allRoutes = $TOOL.data.get($CONFIG.ROUTE_INFO_KEY)
  allRoutes = flatAsyncRoutes(allRoutes)
  menuData.value = filterSideMenu(cloneDeep(allRoutes))

  // 设置选中项
  const matchedRoute = findMenuItemByName(menuData.value, currentPageRoute.name)
  if (matchedRoute) {
    selectedKeys.value = [matchedRoute.name]
    // 处理面包屑和页面标题
    breadcrumb.value = matchedRoute.meta.breadcrumb
    rightBarTitle.value = matchedRoute.title
  } else {
    selectedKeys.value = []
  }
}

// 过滤侧边栏显示的菜单（只保留showMenu为true的）
const filterSideMenu = (tree) => {
  return tree
    .filter(item => item.meta?.showMenu)
    .map(item => ({
      ...item,
      children: item.children ? filterSideMenu(item.children) : []
    }))
}

// 递归查找路由项
const findMenuItemByName = (tree, targetName) => {
  for (const item of tree) {
    if (item.name === targetName) return item;
    if (item.children) {
      const result = findMenuItemByName(item.children, targetName);
      if (result) return result;
    }
  }
  return null;
}
</script>
<style lang="scss">
.components-layout-custom {
  .logo {
    color: #ffffff;
    padding: 20px 0;
    font-size: 18px;
    margin-bottom: 10px;
    text-align: center;
    flex: 1;
  }

  .main-wrapper {
    .collapsed-icon {
      position: absolute;
      left: 0px;
      top: 20px;
      background: rgba(0, 0, 0, .06);
      text-align: center;
      width: 30px;
      height: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 0 20px 20px 0;
      z-index: 100;

      .trigger {
        line-height: 30px;
        font-size: 13px;
        cursor: pointer;
        transition: color 0.3s;

        &:hover {
          color: #1890ff;
        }
      }
    }

    margin: 20px 0 0 0;
    padding: 0;
    min-height: calc(100vh - 20px);
    overflow: initial;
    box-sizing: border-box;
    min-width: 930px;
    width: auto;

    .content-wrapper {
      padding: 15px;
    }
  }

  /* 侧边栏宽度设置  */
  :deep(.ant-layout-sider) {
    flex: 0 0 185px !important;
    max-width: 185px !important;
    min-width: 185px !important;
    width: 185px !important;
    transition: all 0.3s ease !important;
  }
  
  /* 折叠状态宽度 */
  :deep(.ant-layout-sider-collapsed) {
    flex: 0 0 80px !important;
    max-width: 80px !important;
    min-width: 80px !important;
    width: 80px !important;
  }

  /* 选中样式 */
  :deep(.ant-menu-dark.ant-menu-inline .ant-menu-item-selected) {
    background-color: rgba(46, 184, 126, 0.2) !important;
    color: #2eb87e !important;
    border-right: 3px solid #2eb87e !important;
  }
  
  /* 子菜单选中 */
  :deep(.ant-menu-dark .ant-menu-sub .ant-menu-item-selected) {
    background-color: rgba(46, 184, 126, 0.2) !important;
    color: #2eb87e !important;
  }
  
  /* 选中项 hover 效果 */
  :deep(.ant-menu-dark .ant-menu-item-selected:hover) {
    background-color: rgba(46, 184, 126, 0.3) !important;
    color: #2eb87e !important;
  }
  
  /* 当前选中项 */
  :deep(.ant-menu-item-selected) {
    background-color: rgba(46, 184, 126, 0.2) !important;
    color: #2eb87e !important;
  }
}
</style>